<template>
  <div class="admin-users-container">
    <a-card title="管理员用户列表" class="card-with-padding">
      <template #extra>
        <a-button type="primary" @click="showAddModal">
          <plus-outlined /> 添加管理员
        </a-button>
      </template>
      
      <a-table
        :columns="columns"
        :data-source="adminUsers"
        :loading="loading"
        row-key="id"
        size="middle"
        bordered
      >
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="text === 1 ? 'green' : 'red'">
              {{ text === 1 ? '正常' : '禁用' }}
            </a-tag>
          </template>
          
          <template v-if="column.dataIndex === 'createTime'">
            {{ formatDate(text) }}
          </template>
          
          <template v-if="column.dataIndex === 'action'">
            <a-space>
              <a @click="showEditModal(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除此管理员吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="deleteAdmin(record)"
              >
                <a class="danger-text">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 添加/编辑管理员模态框 -->
    <a-modal
      :title="isEdit ? '编辑管理员' : '添加管理员'"
      :visible="modalVisible"
      @cancel="closeModal"
      :footer="null"
      width="500px"
    >
      <a-form
        :model="formState"
        :rules="rules"
        ref="formRef"
        layout="vertical"
        @finish="submitForm"
      >
        <a-form-item label="用户名" name="username" :required="!isEdit">
          <a-input 
            v-model:value="formState.username" 
            placeholder="请输入用户名"
            :disabled="isEdit"
          />
        </a-form-item>
        
        <a-form-item 
          label="密码" 
          name="password" 
          :required="!isEdit"
          v-if="!isEdit"
        >
          <a-input-password 
            v-model:value="formState.password" 
            placeholder="请输入密码"
          />
        </a-form-item>
        
        <a-form-item label="姓名" name="realname">
          <a-input 
            v-model:value="formState.realname" 
            placeholder="请输入姓名"
          />
        </a-form-item>
        
        <a-form-item label="邮箱" name="email">
          <a-input 
            v-model:value="formState.email" 
            placeholder="请输入邮箱"
          />
        </a-form-item>
        
        <a-form-item label="状态" name="status" v-if="isEdit">
          <a-select v-model:value="formState.status">
            <a-select-option :value="1">正常</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item>
          <a-space class="form-buttons">
            <a-button @click="closeModal">取消</a-button>
            <a-button type="primary" html-type="submit" :loading="submitLoading">确定</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import axios from 'axios';

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80
  },
  {
    title: '用户名',
    dataIndex: 'username'
  },
  {
    title: '姓名',
    dataIndex: 'realname'
  },
  {
    title: '邮箱',
    dataIndex: 'email'
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 150
  }
];

// 管理员用户列表
const adminUsers = ref([]);
const loading = ref(false);

// 模态框相关
const modalVisible = ref(false);
const isEdit = ref(false);
const formRef = ref(null);
const submitLoading = ref(false);
const formState = reactive({
  id: undefined,
  username: '',
  password: '',
  realname: '',
  email: '',
  status: 1
});

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度必须在3-20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ]
};

// 获取管理员用户列表
const fetchAdminUsers = async () => {
  try {
    loading.value = true;
    const response = await axios.get('/admin/api/users/admin-users');
    
    if (response.data.code === 0) {
      adminUsers.value = response.data.data;
    } else {
      message.error(response.data.message || '获取管理员列表失败');
    }
  } catch (error) {
    console.error('获取管理员列表错误', error);
    message.error('获取管理员列表失败');
  } finally {
    loading.value = false;
  }
};

// 显示添加管理员模态框
const showAddModal = () => {
  isEdit.value = false;
  resetForm();
  modalVisible.value = true;
};

// 显示编辑管理员模态框
const showEditModal = (record) => {
  isEdit.value = true;
  resetForm();
  
  // 填充表单数据
  Object.keys(formState).forEach(key => {
    if (record[key] !== undefined) {
      formState[key] = record[key];
    }
  });
  
  modalVisible.value = true;
};

// 关闭模态框
const closeModal = () => {
  modalVisible.value = false;
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  
  Object.keys(formState).forEach(key => {
    if (key === 'status') {
      formState[key] = 1;
    } else {
      formState[key] = '';
    }
  });
  formState.id = undefined;
};

// 提交表单
const submitForm = async () => {
  try {
    submitLoading.value = true;
    let response;
    
    if (isEdit.value) {
      // 编辑管理员
      response = await axios.put(`/admin/api/users/admin-users/${formState.id}`, {
        realname: formState.realname,
        email: formState.email,
        status: formState.status
      });
    } else {
      // 添加管理员
      response = await axios.post('/admin/api/users/admin-users', {
        username: formState.username,
        password: formState.password,
        realname: formState.realname,
        email: formState.email
      });
    }
    
    if (response.data.code === 0) {
      message.success(isEdit.value ? '编辑成功' : '添加成功');
      closeModal();
      fetchAdminUsers();
    } else {
      message.error(response.data.message || (isEdit.value ? '编辑失败' : '添加失败'));
    }
  } catch (error) {
    console.error('提交管理员数据错误', error);
    message.error(isEdit.value ? '编辑失败' : '添加失败');
  } finally {
    submitLoading.value = false;
  }
};

// 删除管理员
const deleteAdmin = async (record) => {
  try {
    const response = await axios.delete(`/admin/api/users/admin-users/${record.id}`);
    
    if (response.data.code === 0) {
      message.success('删除成功');
      fetchAdminUsers();
    } else {
      message.error(response.data.message || '删除失败');
    }
  } catch (error) {
    console.error('删除管理员错误', error);
    message.error('删除失败');
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

onMounted(() => {
  fetchAdminUsers();
});
</script>

<style scoped>
.admin-users-container {
  padding: 24px;
}

.card-with-padding {
  margin-bottom: 24px;
}

.danger-text {
  color: #ff4d4f;
}

.form-buttons {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}
</style>